package com.atguigu.msm.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msm.service.MsmService;
import com.atguigu.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmapiController {
    @Resource
    MsmService msmService;
//     注入redis操作模板
    @Autowired
    RedisTemplate<String,String>redisTemplate;
    // 给指定手机号发送短信
    @GetMapping("send/{phoneId}")
    public R sendPhoneCode(@PathVariable("phoneId")String phoneId){
        // 首先从redis中获取手机号
        String code = redisTemplate.opsForValue().get(phoneId);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        String fourBitRandom = RandomUtil.getFourBitRandom();
        Map<String,Object>codes = new HashMap<>();
        codes.put("code",fourBitRandom);
        if(msmService.sendPhoneCode(codes,phoneId)){
            // 将验证码存入redis中并设置有效时间为五分钟
            redisTemplate.opsForValue().set(phoneId,fourBitRandom,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("发送短信失败");
        }
    }
}
